package com.imooc.news_manager_project.common.exception;

import com.imooc.news_manager_project.common.Result;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @project: news_manager_project
 * @author: 13965
 * @date：2023/9/30 13:54
 * @description:
 */
@RestControllerAdvice
public class RRExceptionHandler {

    /**
     * @Author 13965
     * @Date 2022/4/26 8:53
     * @Description TODO 参数效验异常处理
     * @Param ex:
     * @Version 1.0
     **/
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder sb = new StringBuilder("校验失败:");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sb.append(fieldError.getField()).append("：").append(fieldError.getDefaultMessage()).append(", ");
        }
        String msg = sb.toString();
        return new Result(101, msg);
    }

}
